﻿using System;
using System.Threading;
namespace CSUtils {
    public class CBgUpdate {
        Thread thread;
        public string tag=>_tag;
        public string threadName;
        string _tag;
        public int index;
        #if UNITY_EDITOR
        public int frameCount {get;private set;}
        #else
        public int frameCount;
        #endif

        public float deltaTime;
        public float realtimeSinceStartup;

        CBgUpdate() {
        }

        public static CBgUpdate Start(string _tag, Action<CBgUpdate> onBgUpdate, int millisecondsTimeout = 15, int index = -1) {
            var th = new CBgUpdate();
            th._Start(_tag, onBgUpdate, millisecondsTimeout, index);
            return th;
        }

        void _Start(string _tag, Action<CBgUpdate> onBgUpdate, int millisecondsTimeout = 15, int index = -1) {
            this._tag = _tag;
            this.index = index;
            #if CDelayMainTest
            CDelayMain.Delay(0, true).onCallback = delegate(CDelayMain main) {
                if(isEnd == false) {
                    onBgUpdate.Invoke();
                } else {
                    main.isStopDelay = true;
                }
            };
            #else
            thread = new Thread(delegate() {
                while(appIsEnd == false && isEnd == false) {
                    //CLog.i(_tag, $"while()........{CTime.currTimeStr}.....{CTime.deltaTime3}.");
                    Thread.Sleep(millisecondsTimeout);
                    frameCount++;
                    _Bpdate();
                    try {
                        onBgUpdate.Invoke(this);
                    } catch(Exception ex) {
                        CLog.Ex(_tag, "错误", ex);
                    }
                }
            });
            thread.IsBackground = true;
            if(string.IsNullOrEmpty(_tag) == false) {
                threadName = _tag + thread.GetHashCode();
                thread.Name = threadName;
            }
            thread.Start();
            //CDelayBg3.SetThreadId(thread.ManagedThreadId);
            #endif
        }

        public void End() {
            isEnd = true;
        }

        bool isEnd;
        static bool appIsEnd;

        public static void AppEnd() {
            appIsEnd = true;
        }

        public bool isOpenTime {get;set;}

        void _Bpdate() {
            if(isOpenTime) {
                var _startTime = DateTime.Now.ToLocalTime().ToFileTimeUtc();
                var _realtimeSinceStartup = _startTime * 0.0000001f;
                deltaTime = _realtimeSinceStartup - realtimeSinceStartup;
                realtimeSinceStartup = _realtimeSinceStartup;
            }
        }
    }
}
